<template>
  <div class="container">
    <el-form label-position="left" ref="elForm" :model="form" class="ml-3" :rules="rules" size="medium" label-width="100px">
      <el-form-item label="时区:" label-width="170px">
        <select v-model="form.timeZone" placeholder=""  style="width: 400px;">
          <option label="(GMT-12:00) 日界线西" value="GMT-12:00"></option>
          <option label="(GMT-11:00) 中途岛，萨摩亚群岛" value="GMT-11:00"></option>
          <option label="(GMT-10:00) 夏威夷" value="GMT-10:00"></option>
          <option label="(GMT-09:00) 阿拉斯加" value="GMT-09:00"></option>
          <option label="(GMT-08:00) 太平洋时间(美国、加拿大)" value="GMT-08:00"></option>
          <option label="(GMT-07:00) 山地时间(美国和加拿大)" value="GMT-07:00"></option>
          <option label="(GMT-06:00) 中部时间(美国和加拿大)" value="GMT-06:00"></option>
          <option label="(GMT-05:00) 东部时间(美国和加拿大)" value="GMT-05:00"></option>
          <option label="(GMT-04:00) 大西洋时间(加拿大)" value="GMT-04:00"></option>
          <option label="(GMT-03:00) 乔治敦、巴西利亚" value="GMT-03:00"></option>
          <option label="(GMT-02:00) 中大西洋" value="GMT-02:00"></option>
          <option label="(GMT-01:00) 佛得角群岛、亚速尔群岛" value="GMT-01:00"></option>
          <option label="(GMT+00:00) 都柏林、爱丁堡、伦敦" value="GMT+00:00"></option>
          <option label="(GMT+01:00) 阿姆斯特丹、柏林、罗马、巴黎" value="GMT+01:00"></option>
          <option label="(GMT+02:00) 雅典、耶路撒冷" value="GMT+02:00"></option>
          <option label="(GMT+03:00) 巴格达、科威特、莫斯科、伊斯坦布尔、圣彼得堡" value="GMT+03:00"></option>
          <option label="(GMT+04:00) 高加索标准时间" value="GMT+04:00"></option>
          <option label="(GMT+05:00) 伊斯兰堡、卡拉奇、塔什干" value="GMT+05:00"></option>
          <option label="(GMT+06:00) 阿拉木图、达卡" value="GMT+06:00"></option>
          <option label="(GMT+07:00) 曼谷、河内、雅加达、新西伯利亚" value="GMT+07:00"></option>
          <option label="(GMT+08:00) 北京、乌鲁木齐、新加坡、珀斯" value="GMT+08:00"></option>
          <option label="(GMT+09:00) 首尔、东京、大阪、札幌" value="GMT+09:00"></option>
          <option label="(GMT+10:00) 墨尔本、悉尼、堪培拉、布里斯班、霍巴特" value="GMT+10:00"></option>
          <option label="(GMT+11:00) 马加丹、索罗门群岛" value="GMT+11:00"></option>
          <option label="(GMT+12:00) 奥克兰、惠灵顿、斐济" value="GMT+12:00"></option>
          <option label="(GMT+13:00) 努库阿洛法" value="GMT+13:00"></option>
        </select>
      </el-form-item>
      <div class="item title">
        <span class="ng-binding">NTP校时</span>
      </div>
        <el-radio v-model="form.timeMode" label="NTP">NTP校时</el-radio>
        <el-form-item label="NTP服务器地址" label-width="180px">
          <input v-model="form.ntpServerAddress"></input>
        </el-form-item>
        <el-form-item label="NTP端口" label-width="180px">
          <input type="number" v-model.number="form.ntpServerPort"></input>
        </el-form-item>
        <el-form-item label="NTP校时时间间隔(分钟)" label-width="180px">
          <input type="number" v-model.number="form.ntpSyncInterval"></input>
        </el-form-item>
      <div class="item title">
      <span class="ng-binding">手动校时</span>
    </div>
        <el-radio v-model="form.timeMode" label="manual">手动校时</el-radio>

          <el-form-item label="设备时间" label-width="180px">
            <input class="tracking-[0.035rem] pl-[3px]" disabled v-model="current.replaceAll('-', '/')"></input>

          </el-form-item>
          <el-form-item label="设置时间" label-width="180px" class="">
            <input :disabled="sync === 1" v-model="form.localTime" class=""
                   type="datetime-local" step="1"  />
            <el-checkbox @change="syncTime" class="ml-2" v-model="sync" :true-label="1"
            :false-label="0">同计算机时间同步</el-checkbox >
          </el-form-item>
        <el-button class="!mt-8" type="primary" @click="save()" style="margin-left: 0px; width: 120px">保存</el-button>
<!--      </el-form-item>-->
    </el-form>
  </div>
</template>

<script>

  import { timeSync } from "@/api/device/network";
  import { setSysTime,getSysTime } from "@/api/device/system";
export default {
  name: 'index',
  data() {
    return {
      title: "",
      sync: false,
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      current:'',
      time:"",
      form: {
        timeMode:"",
        timeZone:"",
        localTime:"",
        ntpServerAddress:"",
        ntpSyncInterval:"",
        ntpServerPort:""
      },
      intervalId:undefined,
      intervalId2:undefined,
      rules: {
        ntpServerAddress: [
          { required: true, message: '请输入NTP服务器地址', trigger: 'blur' }
        ],
        ntpSyncInterval: [
          { required: true, message: '请输入NTP校时时间间隔', trigger: 'blur' },
          { type: 'number', message: '请输入正确的NTP校时时间间隔', trigger: 'blur' }
        ],
        ntpServerPort: [
          { required: true, message: '请输入NTP服务器端口', trigger: 'blur' },
          { type: 'number', message: '请输入正确的NTP服务器端口', trigger: 'blur' }
        ],
        localTime: [
          { required: true, message: '请选择设置时间', trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    this.getTime();
  },
  beforeDestroy() {
    clearInterval(this.intervalId); // Clear interval when component is destroyed
  },
  methods: {
    getTime() {
      getSysTime().then(res => {
        this.form = res.data;
        this.current = res.data.localTime;
        this.form.localTime = ""
        clearInterval(this.intervalId);
        this.intervalId = setInterval(this.updateTime, 1000);
      });
    },
    syncTime() {
      if (this.sync === 1) {
        this.form.localTime = this.formatDate(new Date());

        this.intervalId2 = setInterval(() => {
          let current = new Date(this.form.localTime);
          current.setSeconds(current.getSeconds() + 1);
          this.form.localTime= this.formatDate( current);
        }, 1000);
      } else {
        clearInterval(this.intervalId2);
      }

    },
    save(){
      const { ntpServerAddress, ntpServerPort, ntpSyncInterval } = this.form;
      if (!ntpServerAddress || ntpServerAddress.trim() === '') {
        this.$message.error('请输入NTP服务器地址');
        return; // 验证失败，中止执行
      }
      // 使用正则表达式验证IP地址或域名
      const ipRegex = /^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/;
      if (!ipRegex.test(ntpServerAddress) && !domainRegex.test(ntpServerAddress)) {
        this.$message.error('NTP服务器地址格式不正确，请输入合法的IP或域名');
        return;
      }

      // 2. 验证NTP端口
      // 检查是否为空或非数字
      if (ntpServerPort === '' || ntpServerPort === null) {
        this.$message.error('请输入NTP端口');
        return;
      }
      // 检查是否为0-65535之间的整数
      if (!Number.isInteger(ntpServerPort) || ntpServerPort < 0 || ntpServerPort > 65535) {
        this.$message.error('NTP端口必须是0到65535之间的整数');
        return;
      }

      // 3. 验证NTP校时时间间隔
      if (ntpSyncInterval === '' || ntpSyncInterval === null) {
        this.$message.error('请输入NTP校时时间间隔');
        return;
      }
      // 检查是否为正整数
      if (!Number.isInteger(ntpSyncInterval) || ntpSyncInterval <= 0) {
        this.$message.error('NTP校时时间间隔必须是正整数');
        return;
      }
      this.form.localTime = this.form.localTime.replace('T', ' ')
      setSysTime(this.form).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.getTime();
      }).catch(err => {
        this.$message({
          message: '保存失败',
          type: 'error'
        });
      });
    },
    pad(n) {

      return n.toString().padStart(2, '0');
    },
    formatDate(date) {

      const year = date.getFullYear();
      const month = this.pad(date.getMonth() + 1); // Month is 0-indexed
      const day = this.pad(date.getDate());
      const hours = this.pad(date.getHours());
      const minutes = this.pad(date.getMinutes());
      const seconds = this.pad(date.getSeconds());
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    syn(){
      let tem = new Date();
      this.form.localTime = this.formatDate(tem)
    },
    updateTime() {

      let temp = new Date(this.current)
      temp.setSeconds(temp.getSeconds() + 1);
      this.current = this.formatDate(temp);
      // this.time = this.formatDate(this.current);
    },
  }
}
</script>

<style scoped>
.container {
  width: 70%;
}

.button {
  margin-left: 15%;
}
.el-form-item .el-form-item {
  margin-bottom: 10px;
}
input {
  width: 180px;
}

 .item  {
  background-color: #F2F2F2;
  font-weight: 700;
  margin-top: 10px;
}

 .item.title {
  background-color: #F2F2F2;
  font-weight: 700;
  padding-left: 15px;
  margin-top: 10px;
   margin-bottom: 5px;
}
.item {
  height: 30px;
  line-height: 30px;
}
</style>
